package net.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import net.sf.json.JSONString;
import net.sf.json.JsonConfig;
import net.sf.json.processors.DefaultValueProcessor;
import net.sf.json.processors.JsonValueProcessor;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author: jiangxiangwei
 * @date: Dec 18, 2008
 */
public class ToolsAction extends ActionSupport {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    Map model = null;
    private Logger log = Logger.getLogger(this.getClass());


    protected int code = 0;
    protected String msg = "操作成功！";
    protected String expMsg = "";

    public ToolsAction() {
        model = new HashMap();
    }

    public Map getModel() {
        return model;
    }

    public void setModel(Map model) {
        this.model = model;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getExpMsg() {
        return expMsg;
    }

    public void setExpMsg(String expMsg) {
        this.expMsg = expMsg;
    }

    public Object findValue(String name) {
        return ActionContext.getContext().getValueStack().findValue(name);
    }

    public void setValue(String name, Object value) throws Exception {
        ActionContext.getContext().getValueStack().setValue(name, value);
    }

    /**
     * 将字符串向前台输出json结果
     *
     * @param code
     * @param str
     */
    public void setResult(String code, String str) {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        try {
            PrintWriter out = response.getWriter();
            out.println(strToJson(code, Tools.string2Json(str)));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将list转为json输出前台
     *
     * @param code
     * @param list
     */
    public void setResult(String code, List list) {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        try {
            PrintWriter out = response.getWriter();
            out.println(listToJson(code, list));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将list转为json输出前台  带分页信息
     *
     * @param code
     * @param list
     */
    public void setResult(String code, PageList list) {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        try {
            PrintWriter out = response.getWriter();
            out.println(pageListToJson(code, list));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将map转为json输出前台
     *
     * @param code
     * @param map
     */
    public void setResult(String code, Map map) {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        try {
            PrintWriter out = response.getWriter();
            out.println(mapToJson(code, map));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 字符串转为json
     *
     * @param code
     * @param str
     * @return
     */
    public String strToJson(String code, String str) {
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("code:\"").append(code).append("\",");
        sb.append("data:[\"").append(str).append("\"]");
        sb.append("}");
        log.debug(sb);
        return sb.toString();
    }

    /**
     * map转为json
     *
     * @param code
     * @param map
     * @return
     */
    public String mapToJson(String code, Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("code:\"").append(code).append("\",");
        sb.append("data:").append(Tools.toJsonByMap(map));
        sb.append("}");
        sb.replace(sb.length() - 2, sb.length() - 1, "");
        log.debug(sb);
        return sb.toString();
    }

    /**
     * list转为json
     *
     * @param code
     * @param list
     * @return
     */
    public String listToJson(String code, List list) {
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("code:\"").append(code).append("\",");
        sb.append("data:").append(Tools.toJsonByList(list))
                .append("}");
        sb.replace(sb.length() - 2, sb.length() - 1, "");
        log.debug(sb);
        return sb.toString();
    }

    /**
     * list 转为json  带分页信息
     *
     * @param code
     * @param pList
     * @return
     */
    public String pageListToJson(String code, PageList pList) {
//        Map map = pList.getPageMap();
//        StringBuffer page = new StringBuffer();
//        page.append("pages:{")
//                .append("TOTALCOUNT:\"").append(map.get("TOTALCOUNT")).append("\",")
//                .append("CURPAGE:\"").append(map.get("CURPAGE")).append("\",")
//                .append("TOTALPAGE:\"").append(map.get("TOTALPAGE")).append("\",")
//                .append("PAGESIZE:\"").append(map.get("PAGESIZE")).append("\"")
//                .append("}");
//
//        StringBuffer sb = new StringBuffer();
//        List list = pList.getDataList();
//        sb.append("{");
//        sb.append("code:\"").append(code).append("\",");
//        sb.append("data:").append(tools.toJsonByList(list))
//                .append(",");
//        sb.replace(sb.length() - 2, sb.length() - 1, "");
//        sb.append(page).append("}");
//        log.debug(sb);

        List list = pList.getDataList();
        Map map = pList.getPageMap();

        Map jsonMap = new HashMap();
        jsonMap.put("code",code);
        jsonMap.put("data", list);
        jsonMap.put("pages", map);

        JSONObject js = JSONObject.fromObject(jsonMap);
        return js.toString();
    }

    /**
     * 从rquest中截取参数，放入map中
     *
     * @param request
     * @return
     */
    public Map parserRequest(HttpServletRequest request) {
        Map map = new HashMap();
        Enumeration enume = request.getParameterNames();
        while (enume.hasMoreElements()) {
            String pName = (String) enume.nextElement();
            String value =request.getParameter(pName);
            if (value != null && !value.equals(""))
                map.put(pName, value);
            value = null;
        }
        return map;
    }

    public HttpServletResponse getResponse() {
        return (HttpServletResponse) ActionContext.getContext().get(
                "com.opensymphony.xwork2.dispatcher.HttpServletResponse");
    }

    public HttpServletRequest getRequest() {
        return (HttpServletRequest) ActionContext.getContext().get(
                "com.opensymphony.xwork2.dispatcher.HttpServletRequest");
    }

    public Map getSession() {
        return ActionContext.getContext().getSession();
    }
    public String getParamter(String paramName) {
        List list = new ArrayList();
        try {
            list = Arrays.asList((String[]) getRequest().getParameterMap().get(paramName));
        } catch (NullPointerException e) {
//            log.error("读取参数->" + paramName + "=" + e.getMessage());
        }
        String val = "";
        for (int i = 0; i < list.size(); i++)
            val += (String) list.get(i) + ',';

        return val.length() > 0 ? (val.substring(0, val.length() - 1)) : val;
    }
    public String getResult() {
        //保存数据
        // JsonHelp.getRequest().setAttribute("data",resultMapData);
        String result = getParamter("RESULT_TYPE");
        return result.length() == 0 ? SUCCESS : result;
    }

    public String getExceptionMessage(Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        return sw.toString().replaceAll("\r\n","<br>");
    }
}
